# -*- coding: utf-8 -*-
# 定时任务
import tushare as ts
import logging
from djangoProject import settings
import datetime
from sqlalchemy import create_engine
import tushare.stock.classifying as cl

logger = logging.getLogger("django")


# 获取行业分类数据
def get_industry_classified():
    print(ts.get_industry_classified())


# 获取行业分类数据
def get_hs300s():
    print(ts.get_hs300s())


# 初始化股票分类（只初始化行业、概念、地域）
def init_classifying(day):
    logger.info("init_classifying任务开始………………")
    logger.info(settings.MYSQL_ENGINE_URL)
    try:
        logger.info("已获取engine……………………")
        # 行业
        df = ts.get_industry_classified()
        df['date'] = datetime.datetime.strptime(day, "%Y-%m-%d")
        engine = create_engine(settings.MYSQL_ENGINE_URL)
        # 存入数据库
        df.to_sql('ts_industry_classified', engine, if_exists='replace', index=False)

        # 概念
        df1 = ts.get_concept_classified()
        df1['date'] = datetime.datetime.strptime(day, "%Y-%m-%d")
        engine = create_engine(settings.MYSQL_ENGINE_URL)
        # 存入数据库
        df1.to_sql('ts_concept_classified', engine, if_exists='replace', index=False)

        # 地域
        df2 = ts.get_area_classified()
        df2['date'] = datetime.datetime.strptime(day, "%Y-%m-%d")
        engine = create_engine(settings.MYSQL_ENGINE_URL)
        # 存入数据库
        df2.to_sql('ts_area_classified', engine, if_exists='replace', index=False)

        # dfcf概念板块
        df3 = cl.get_concepts()
        df3['date'] = datetime.datetime.strptime(day, "%Y-%m-%d")
        df3 = df3.rename(index=str, columns={"change": "changev"})
        engine = create_engine(settings.MYSQL_ENGINE_URL)
        # 存入数据库
        df3.to_sql('ts_concepts', engine, if_exists='append', index=False)
    except Exception as e:
        logger.error("执行init_classifying时异常, code=%s", e.code)
    logger.info("………………init_classifying任务完成")
